package com.cindata

import grails.transaction.Transactional

@Transactional
class RiskWarningFlowStageEventService
{
    ComponentService componentService

    def initFlowStageEvent(RiskWarning riskWarning, Workflow workflow)
    {
        def workflowStages = WorkflowStage.findAllByWorkflow(workflow)
        for (
            workflowStage in
                workflowStages)
        {
            workflowStage?.events?.each {
                def riskWarningFlowStageEvent = new RiskWarningFlowStageEvent()
                riskWarningFlowStageEvent.isSynchronous = it?.isSynchronous
                riskWarningFlowStageEvent.executeSequence = it?.executeSequence
                riskWarningFlowStageEvent.log = it?.log
                riskWarningFlowStageEvent.component = it?.component
                riskWarningFlowStageEvent.flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, workflowStage?.stage)
                if (riskWarningFlowStageEvent.validate())
                {
                    riskWarningFlowStageEvent.save flush: true
                }
                else
                {
                    println riskWarningFlowStageEvent.errors
                }
            }
        }
    }

    def evaluate(RiskWarningFlowStage flowStage, String executeSequence)
    {
        def events = []
        if (executeSequence == 'positive')
        {
            events = RiskWarningFlowStageEvent.findAll("from RiskWarningFlowStageEvent where flowStage.id = ${flowStage?.id} and executeSequence > 0 order by executeSequence ASC")
        }
        else if (executeSequence == 'negative')
        {
            events = RiskWarningFlowStageEvent.findAll("from RiskWarningFlowStageEvent where flowStage.id = ${flowStage?.id} and executeSequence < 0 order by executeSequence ASC")
        }
        if (events?.size() > 0)
        {
            events?.each {
                def event = it
                if (event?.isSynchronous)
                {
                    evaluate2(event)
                }
                else
                {
                    Thread.start {
                        evaluate2(event)
                    }
                }
            }
        }
    }

    def evaluate2(RiskWarningFlowStageEvent eventObject)
    {
        def shell = new GroovyShell()
        def closure
        def result
        def event = RiskWarningFlowStageEvent.find("from RiskWarningFlowStageEvent where id = ${eventObject?.id}")

        try
        {
            event.startTime = new Date()
            if (event?.component)
            {
                result = componentService.evaluate event?.component, event?.flowStage?.riskWarning
            }
            event.log = result
            event.endTime = new Date()
            event.save flush: true
        }
        catch (Exception e)
        {
            event.log = e
            event.endTime = new Date()
            event.save flush: true
        }
    }
}